package com.janwen.spring.jdbc.datasource;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Component;

@Component("datasourceLeak")
public class DatasourceLeak extends AbstractJdbctemplate {

	
	public void asynchrUpdate(DatasourceLeak dsl,String name){
		DataThread dt = new DataThread(dsl, name);
		dt.start();
	}
	public void updateStuff(String name) throws SQLException, InterruptedException {
		String sql = "UPDATE stuff sf SET sf.age=sf.age+10 WHERE sf.name=?";
		//通过DataSourceUtils获取数据连接 
		Connection connection = DataSourceUtils.doGetConnection(getJdbcTemplate().getDataSource());
	//	Connection connection = getJdbcTemplate().getDataSource()
		//		.getConnection();
		getJdbcTemplate().update(sql, name);
		Thread.sleep(1000);
		//必须手动释放链接
		connection.close();
	}
	
	
	private static class DataThread extends Thread{
		private DatasourceLeak datasourceLeak;
		private String name;
		public DataThread(DatasourceLeak datasourceLeak,String name){
			this.datasourceLeak = datasourceLeak;
			this.name = name;
		}
		
		@Override
		public void run(){
			try {
				datasourceLeak.updateStuff(name);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	static final Log logger = LogFactory.getLog(DatasourceLeak.class);
	public static void reportDatasoure(BasicDataSource dataSource){
		logger.info("[active:idle]-[" + dataSource.getNumActive() + ":" + dataSource.getNumIdle() + "]");
	}

	
	public static void main(String[] args) throws Exception {
		String name = "bing";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("jdbcDatasourceLeak.xml");
		DatasourceLeak dsl = (DatasourceLeak) applicationContext.getBean("datasourceLeak");
		BasicDataSource basicDataSource = (BasicDataSource) applicationContext.getBean("dataSource");
		dsl.reportDatasoure(basicDataSource);
		dsl.asynchrUpdate(dsl, name);
		Thread.sleep(500);
		dsl.reportDatasoure(basicDataSource);
		Thread.sleep(2000);
		dsl.reportDatasoure(basicDataSource);
		dsl.asynchrUpdate(dsl, name);
		Thread.sleep(500);
		dsl.reportDatasoure(basicDataSource);
		Thread.sleep(2000);
		dsl.reportDatasoure(basicDataSource);
		
	}
}
